package com.woniuxy.utils;

import com.woniuxy.shiro.utils.MyJsonWebToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器，
 * preHandle(第一关，所有的过滤器，优先进入这个方法，返回为true才允许controller)
 * -->isAccessAllowed
 * -->isLoginAttempt
 * -->executeLogin
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {
    /**
     * 在这里需要解决的其实只有跨域的问题，全局跨域问题的解决方案
     * 虽然是前端解决跨域，但是我们还是要知道这里怎么配置
     * 这个过滤器，是登录成功以后，使用JWT进行请求访问的时候，执行的过滤器
     * shiro自带的过滤器BasicHttpAuthenticationFilter它只支持账号密码验证，不支持我们的JWT
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 尝试登录，看是否已经登录了
     * 没有登录跳转401页面，登录成功就进入shiro的subject.login(MyJsonWebToken)
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 必须确保前端有token，我们才能通过token执行登录流程
        //前端token是必须登录成功以后，返回给前端这个token，然后前端把token存起来命名key=Authorization
        if(isLoginAttempt(request,response)){
            try {
                executeLogin(request,response);
            } catch (Exception e) {
                e.printStackTrace();
//                如果说出现异常，我们就需要返回浏览器一个401信息
                response401(request,response);
            }
        }
        return true;
    }

    private void response401(ServletRequest request, ServletResponse response) {
        HttpServletResponse response1 = (HttpServletResponse) response;
        try {
            //这里会跳转到controller
            response1.sendRedirect("/401");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("JWTFilter.response401:"+e.getMessage());
        }
    }

    /**获取请求头的信息，拿到浏览器发给我们的 token 请求头中有Authorization，我们才继续没有，抛异常
     * 没有的话 就应该跳转到登录页面
    */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        return authorization!=null;
    }

    /**
     * 最后的subject.login 执行shiro的登录认证流程
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//        从请求头中获取token
        String token = httpServletRequest.getHeader("Authorization");
        MyJsonWebToken myJsonWebToken = new MyJsonWebToken(token);
        //真正执行我们的登录方法，要进入到我们的自定义域的Authentication认证方法中
        getSubject(request,response).login(myJsonWebToken);
        return true;
    }
}
